package com.zhang.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhang sq
 * @date : 2022/6/6 8:47
 * 进度条
 **/
@ServerEndpoint(value = "/ws/progressBar/test")
@Component
public class ApiProgressBarWebSocket {

    private static final Logger log = LoggerFactory.getLogger(ApiProgressBarWebSocket.class);

    private Session session;
    private RemoteEndpoint.Basic remoteEndpoint = null;


    @OnOpen
    public void onOpen(Session session) throws Exception {
        this.session = session;
        remoteEndpoint = session.getBasicRemote();
        WebSocketUtil.sendMsg(remoteEndpoint, "Connection successful !");
    }

    @OnClose
    public void onClose() {
        log.debug("[debug-progressBar-websocket]onClose");
    }

    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
        log.debug("[debug-progressBar-websocket][{}]onError", t.getMessage());
    }

    @OnMessage
    public void onMessage(String message) {
        Map<String,Object> map = new HashMap<>();
        try {
            log.debug("[debug-progressBar-websocket]接收到的信息为：[{}]", message);
            WebSocketUtil.sendMsg(remoteEndpoint, "request failure: 请求数据格式不合法");
            map.put("planResultApiId","planResultApiId");
            map.put("jobId","jobId");
            map.put("sum","sum");
            map.put("executeNum","executeNum");
            WebSocketUtil.sendData(remoteEndpoint, map);
            closeSession();
        } catch (Exception | Error e) {
            e.printStackTrace();
            WebSocketUtil.sendMsg(remoteEndpoint, String.format("异常退出，%s", e.getMessage()));
            WebSocketUtil.sendData(remoteEndpoint, map);
            closeSession();
        }
    }

    private void closeSession() {
        if (session.isOpen()) {
            try {
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
